import { Avatar, Icon, Menu, Spin, Modal, Form, Input,message } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import React from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import SetIcon from '@/pages/sys/user/components/SetIcon';
import AxiosUtil from '@/tool/AxiosUtil';

class AvatarDropdown extends React.Component {
  state = {
    visible: false,
  };

  onMenuClick = event => {
    const { key } = event;

    if (key === 'logout') {
      AxiosUtil.get('/sys/oauth/logout')
        .then(() => {
          window.location.href = '/login';
        });
    } else if (key === 'updatePwd') {
      this.handleOk();
    }

    // router.push(`/account/${key}`);
  };

  // 提交
  // eslint-disable-next-line react/sort-comp,@typescript-eslint/no-unused-vars
  handleSubmit = e => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        AxiosUtil.put('/sys/user/update/pwd', AxiosUtil.json2FormData(values)).then(() => {
          message.success('密码修改成功');
          this.handleCancel();
        })
      }
    });
  };

  render() {
    const {
      currentUser = {
        avatar: '',
        name: '',
      },
      menu,
    } = this.props;
    const menuHeaderDropdown = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.onMenuClick}>
        {menu && (
          <Menu.Item key="center">
            <Icon type="user" />
            <FormattedMessage id="menu.account.center" defaultMessage="account center" />
          </Menu.Item>
        )}
        {menu && (
          <Menu.Item key="settings">
            <Icon type="setting" />
            <FormattedMessage id="menu.account.settings" defaultMessage="account settings" />
          </Menu.Item>
        )}
        {menu && <Menu.Divider />}

        <Menu.Item key="updatePwd">
          <Icon type="key" />
          <FormattedMessage id="menu.account.updatePwd" defaultMessage="updatePwd" />
        </Menu.Item>
        <Menu.Item key="logout">
          <Icon type="logout" />
          <FormattedMessage id="menu.account.logout" defaultMessage="logout" />
        </Menu.Item>
      </Menu>
    );

    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
    };
    return currentUser && currentUser.name ? (
      <span>
        <HeaderDropdown overlay={menuHeaderDropdown}>
          <span className={`${styles.action} ${styles.account}`}>
            <SetIcon key={currentUser.photo} photo={currentUser.photo} style={{ position: 'relative', top: -3 }} size="mini"/>
            <span className={styles.name} style={{ marginLeft: 5, fontSize: 12 }}>{currentUser.loginName}</span>
          </span>
        </HeaderDropdown>
        <Modal
          title="Basic Modal"
          visible={this.state.visible}
          onOk={this.handleSubmit.bind(this)}
          onCancel={this.handleCancel}
        >
          <Form {...formItemLayout}>
            <Form.Item label="旧密码" hasFeedback>
                {getFieldDecorator('oldPwd', {
                  rules: [
                    {
                      required: true,
                      message: '请输旧密码',
                    },
                    {
                      validator: this.validateToNextPassword,
                    },
                  ],
                })(<Input.Password/>)}
              </Form.Item>
            <Form.Item label="密码" hasFeedback>
                {getFieldDecorator('newPwd', {
                  rules: [
                    {
                      required: true,
                      message: '请输入密码',
                    },
                    {
                      validator: this.validateToNextPassword,
                    },
                  ],
                })(<Input.Password/>)}
              </Form.Item>
              <Form.Item label="确认密码" hasFeedback>
                {getFieldDecorator('confirm', {
                  rules: [
                    {
                      required: true,
                      message: '请输入确认密码',
                    },
                    {
                      validator: this.compareToFirstPassword,
                    },
                  ],
                })(<Input.Password onBlur={this.handleConfirmBlur}/>)}
              </Form.Item>
          </Form>
        </Modal>
      </span>
    ) : (
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    );
  }

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  handleOk = e => {
    this.setState({
      visible: true,
    });
  };

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  handleCancel = e => {
    this.setState({
      visible: false,
    });
  };

  compareToFirstPassword = (rule, value, callback) => {
    const { form } = this.props;
    if (value && value !== form.getFieldValue('newPwd')) {
      callback(' 两次输入的密码不正确!');
    } else {
      callback();
    }
  };

  validateToNextPassword = (rule, value, callback) => {
    const { form } = this.props;
    if (value && this.state.confirmDirty) {
      form.validateFields(['confirm'], { force: true });
    }
    callback();
  };
}

const AvatarDropdownForm = Form.create({ name: 'AvatarDropdown' })(AvatarDropdown);

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(AvatarDropdownForm);
